import requests
import json
import time
from datetime import timedelta, date

counter = 0
total = 0
time_to = date.today()
print(time_to)
n = 0
while n < 1000:
    n += 1
    time_from = time_to - timedelta(days=30)
    # print(f"开始时间：{time_from}，结束时间：{time_to}")
    url = "https://api.bilibili.com/x/web-interface/newlist_rank"
    params = {
        'main_ver': 'v3',
        'search_type': 'video',
        'view_type': 'hot_rank',
        'copy_right': '-1',
        'new_web_tag': '1',
        'order': 'click',
        'cate_id': '247',
        'page': 1,
        'pagesize': '30',
        'time_from': time_from.strftime("%Y%m%d"),
        'time_to': time_to.strftime("%Y%m%d"),
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    response = requests.get(url, params=params, headers=headers)
    result = response.content.decode()
    result = json.loads(result)
    numResults = result["data"]["numResults"]
    if not result['data']['result']:  # 如果result['data']['result']为空，则跳过本次循环
        time.sleep(2)
        print("没有返回数据...")
        continue
    total += numResults

    # 特定时间段内页面数量
    numPages = result["data"]["numPages"]
    for page in range(1, numPages + 1):
        params = {
            'main_ver': 'v3',
            'search_type': 'video',
            'view_type': 'hot_rank',
            'copy_right': '-1',
            'new_web_tag': '1',
            'order': 'click',
            'cate_id': '247',
            'page': page,
            'pagesize': '30',
            'time_from': time_from.strftime("%Y%m%d"),
            'time_to': time_to.strftime("%Y%m%d"),
        }
        response = requests.get(url, params=params, headers=headers)
        result = response.content.decode()
        result = json.loads(result)
        if not result['data']['result']:  # 如果result['data']['result']为空，则跳过本次循环
            time.sleep(2)
            print("没有返回数据...")
            page -= 1
            continue
        for item in result['data']['result']:
            counter += 1
            title = item['title']
            play = item['play']
            print(counter, title, play)

    print(f"开始时间：{time_from}，结束时间：{time_to}", numResults, total)
    time_to = time_from
